const Router = require("koa-router");
const bodyParser = require("koa-bodyparser");
const article = require("../utils/sql");

const myfile = new Router();
myfile.use(bodyParser());

const fetchDataAndFormat = async (ctx, getDataFunction, username) => {
  try {
    const params = ctx.request.body;
    const { id } = params;
    const data = await getDataFunction(id);
    const destructuredData = data.data.map(
      ({
        id,
        user_id,
        filename,
        size,
        type,
        folder_id,
        created_at,
        shared,
        recycle,
        relativeFilePath,
      }) => ({
        id,
        user_id,
        filename,
        size,
        type,
        folder_id,
        created_at,
        shared,
        recycle,
        relativeFilePath: `http://192.168.31.222:3000/fileUploadDownload/image/${username}/${relativeFilePath}`,
      })
    );

    // 过滤recycle为1的数据
    const filterData = destructuredData.filter((item) => item.recycle === 0);

    ctx.body = {
      code: 200,
      msg: "获取成功",
      data: filterData,
    };
  } catch (error) {
    console.error("Error fetching data:", error);
    ctx.status = 500;
    ctx.body = {
      code: 500,
      msg: "Internal Server Error",
    };
  }
};

// 视频文件
myfile.post("/video", async (ctx) => {
  const username = ctx.request.body.username;
  await fetchDataAndFormat(ctx, article.getVideo, username);
});

// 音频文件
myfile.post("/audio", async (ctx) => {
  const username = ctx.request.body.username;
  await fetchDataAndFormat(ctx, article.getAudio, username);
});

// 文档文件
myfile.post("/doc", async (ctx) => {
  const username = ctx.request.body.username;
  await fetchDataAndFormat(ctx, article.getDoc, username);
});

// 图片文件
myfile.post("/image", async (ctx) => {
  const username = ctx.request.body.username;
  await fetchDataAndFormat(ctx, article.getImg, username);
});

module.exports = myfile;
